package com.itheima.health.webcontroller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.health.constants.MessageConstant;
import com.itheima.health.constants.RedisConstant;
import com.itheima.health.constants.RedisMessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.utils.SMSUtils;
import com.itheima.health.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 验证码控制层
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;
    /**
     * 预约发送验证码
     */
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone) {
        boolean flag = false;
        try {
            // 生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            String validateCode = String.valueOf(code);

            // 将验证码信息放入redis中,设置有效时间300S
            Jedis jedis = jedisPool.getResource();
            // 手机号码作为key
            jedis.setex(telephone + RedisMessageConstant.SENDTYPE_ORDER,300,validateCode);
            // 调用工具发送验证码,发送成功返回true
            if (false) {
                flag = SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, validateCode);
            }
            System.out.println("key" + telephone + "---code----  " + validateCode);
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    /**
     * 用户登录发送验证码
     */
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone) {
        boolean flag = false;
        try {
            // 生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            String validateCode = String.valueOf(code);

            // 将验证码信息放入redis中,设置有效时间300S
            Jedis jedis = jedisPool.getResource();
            // 手机号码作为key
            jedis.setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN,300,validateCode);
            // 调用工具发送验证码,发送成功返回true
            if (false) {
                flag = SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE, telephone, validateCode);
            }
            System.out.println("key" + telephone + "---code----  " + validateCode);
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}
